/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.cn.xiaonuo.tcrfinance.sysmgmt.service.impl;
import com.cn.xiaonuo.common.constant.SystemConstant;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysMenuEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserTokenHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysMenuHpcMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserHpcMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserTokenHpcMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.ShiroHpcService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroHpcServiceImpl implements ShiroHpcService {
    @Autowired
    private SysMenuHpcMapper sysMenuMapper;
    @Autowired
    private SysUserHpcMapper sysUserMapper;
    @Autowired
    private SysUserTokenHpcMapper sysUserTokenMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == SystemConstant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuMapper.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenHpcEntity queryByToken(String token) {
        return sysUserTokenMapper.queryByToken(token);
    }

    @Override
    public SysUserHpcEntity queryUser(Long userId) {
        return sysUserMapper.selectById(userId);
    }
}
